import React, {Component} from "react";
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {Card, Input} from 'antd';
import _ from 'lodash'
import * as CounterActions from '../actions/wtgprs';
import Config from './config';


const Serialport = require("serialport");

const Search = Input.Search;


class DataView extends Component {
  constructor(props) {
    super(props);
    const config = new Config();
    const $t = this;
    $t.state = {
      list: [],
      data: null,
      devNo: "WT460000002C",
      tick:true,
    };

    $t.port = undefined;

    $t.componentWillMount = () => {
      $t.state.list = [
        {
          hide:true,
          name: "加速度X",
          index: 1,
          suffix: "g"
        }, {
          hide:true,
          name: "加速度Y",
          index: 2,
          suffix: "g"
        }, {
          hide:true,
          name: "加速度Z",
          index: 3,
          suffix: "g"
        },
        {
          hide:true,
          name: "角速度X",
          index: 4,
          suffix: "°/s"
        }, {
          hide:true,
          name: "角速度Y",
          index: 5,
          suffix: "°/s"
        }, {
          hide:true,
          name: "角速度Z",
          index: 6,
          suffix: "°/s"
        },
        {
          hide:false,
          name: "角  度  X",
          index: 7,
          suffix: "°"
        }, {
          hide:false,
          name: "角  度  Y",
          index: 8,
          suffix: "°"
        }, {
          hide:false,
          name: "角  度  Z",
          index: 9,
          suffix: "°"
        },
        {
          hide:true,
          name: "磁  场  X",
          index: 10,
          suffix: "T"
        }, {
          hide:true,
          name: "磁  场  Y",
          index: 11,
          suffix: "T"
        }, {
          hide:true,
          name: "磁  场  Z",
          index: 12,
          suffix: "T"
        },
        {
          hide:true,
          name: "温    度",
          index: 13,
          suffix: "°C"
        },
        {
          hide:false,
          name: "经    度",
          index: 25,
          suffix: "°"
        },
        {
          hide:false,
          name: "纬   度",
          index: 26,
          suffix: "°"
        },
        {
          hide:false,
          name: "海    拔",
          index: 27,
          suffix: "M"
        },
        {
          hide:true,
          name: "采样间隔",
          index: 32
        },
      ];

      const {comId, wtgprsDevNo} = config.load();
      if (wtgprsDevNo) {
        $t.state.devNo = wtgprsDevNo;
      }

      if (comId) {
        $t.openSerialport(comId);
      }
    };

    $t.calcAngle = (dH, dL) => {
      const angle = ((dH * 256) + dL) / 32768 * 180;

      return angle < 180 ? angle.toFixed(2) : (angle - 360).toFixed(2);
    };

    $t.calcGPS = int => {
      const zoom = 10000000;
      // eslint-disable-next-line radix
      return parseFloat(parseInt(int / zoom) + (int % zoom)/60 / 100000).toFixed(6);
    };

    $t.comId = undefined;
    $t.openSerialport = (comId, baudrate) => {

      if ($t.comId === comId && $t.port) {
        try {
          $t.port.close();
        } catch (e) {
          console.error(e.toString());
        }
      }

      const port = new Serialport(comId, {
        baudRate: baudrate || 115200,// 波特率
        dataBits: 8,// 数据位
        parity: 'none',// 奇偶校验
        stopBits: 1,// 停止位
        flowControl: false,
        autoOpen: false // 不自动打开
      }, false);

      port.open(error => {
        if (error) {
          console.error(error.toString());
        } else {
          /*
           *设置回传全部数据，
           */

          let buffer = Buffer.from([0xff, 0xaa, 0x02, 0xff, 0xff], 'hex');
          port.write(buffer);

          /*
           *频率0.5HZ
           */
          buffer = Buffer.from([0xff, 0xaa, 0x03, 0x02, 0x00], 'hex');
          port.write(buffer);

          /*
           *保存配置
           */
          buffer = Buffer.from([0xff, 0xaa, 0x00, 0x00, 0x00], 'hex');
          port.write(buffer);

          port.on("data", list => {
            // eslint-disable-next-line no-plusplus
            for (let i = 0; i < list.length; i++) {
              const {angleFlush, wtgprs} = $t.props;

              if (list[i] === 0x55 && list[i + 1] === 0x53) {
                const data = $t.state.data ? _.cloneDeep($t.state.data) : [];
                data[7] = $t.calcAngle(list[i + 3], list[i + 2]);
                data[8] = $t.calcAngle(list[i + 5], list[i + 4]);
                data[9] = $t.calcAngle(list[i + 7], list[i + 6]);

                $t.setState({data});
                angleFlush(data)
              }

              if (list[i] === 0x55 && list[i + 1] === 0x56) {
                const data = $t.state.data ? _.cloneDeep($t.state.data) : [];
                // eslint-disable-next-line no-bitwise
                const height = list[i + 6] + list[i + 7] << 8 + list[i + 8] << 16 + list[i + 9] << 24;
                data[27] = (height / 100).toFixed(2);
                console.log("海拔", data[27]);
                $t.setState({data});
              }

              if (list[i] === 0x55 && list[i + 1] === 0x57) {
                const data = $t.state.data ? _.cloneDeep($t.state.data) : [];

                // eslint-disable-next-line no-bitwise
                const lon = $t.calcGPS(list[i + 2] + list[i + 3]*256 + list[i + 4]*256*256 + list[i + 5]*256*256*256);
                // eslint-disable-next-line no-bitwise
                const lat = $t.calcGPS(list[i + 6] + list[i + 7]*256+ list[i + 8]*256*256 + list[i + 9]*256*256*256);
                // eslint-disable-next-line no-loop-func
                // _.debounce(()=>{
                //
                // },3000)

                $t.tranferGps(lon,lat, (lon1, lat1) => {
                  console.log("经度",lon1, "纬度", lat1);
                  data[25] = lon1;
                  data[26] = lat1;
                  wtgprs(data);
                  $t.setState({data});
                });
              }
            }
          })
        }
      });

      if ($t.comId !== comId && $t.port) {
        try {
          $t.port.close();
        } catch (e) {
          console.error(e.toString());
        }
      }

      $t.comId = comId;
      $t.port = port;
    };
    let count = 0;
    setInterval(()=>{
      const {tick} = $t.state;
      $t.setState({tick:!tick});
    },1000);
    $t.tranferGps = (lan, lat, cb) => {
      if(lan && lat){
        $.get(`http://api.map.baidu.com/geoconv/v1/?coords=${lan},${lat}&from=1&to=5&ak=2BoFGed2qBO6w1ScnedtIMLp`, ({status, result}) => {
          if (status === 0) {
            cb(result[0].x.toFixed(6), result[0].y.toFixed(6))
          } else {
            console.error(status, "转换错误");
          }
        });
      }
    };


    $t.render = () => {
      const {list, data,tick} = $t.state;
      const subList  = _.filter(list,row=>!row.hide);

      return (
        <Card title="姿态传感器" bordered className="data-view">
          <div className="list">
            {subList.map(({name,index, suffix}) =>
              (<div key={name} className="li">
                <label style={{color: "#fff", fontSize: "14px", textAlign: "center"}}>{name} ：</label>
                <span style={{
                  width: "80px",
                  display: "inline-block",
                  fontSize: "14px",
                  height: "28px",
                  color: "#00FF33",
                  textAlign: "right"
                  // eslint-disable-next-line no-nested-ternary
                }}>{data ? data[index] : (tick?"-":".")}</span>
                <span style={{
                  fontSize: "14px",
                  height: "28px",
                  color: "#00FF33",
                  textAlign: "left",
                  paddingLeft: "5px"
                }}>{data && suffix ? suffix : ""}</span>
              </div>))}
          </div>
        </Card>
      )
    }
  }
}

function mapStateToProps(state) {
  return {};
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(CounterActions, dispatch);
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(DataView);
